<template>
  <div class="wrapper">
    <form v-if="!showPhoneLogin">
      <!--解决浏览器自动填充账号密码的问题-->
      <input type="text" name="username" style="position: absolute;z-index: -99;height: 0;">
      <input type="password" name="password" style="position: absolute;z-index: -99;height: 0;">
      <md-field>
        <md-input-item name="userName" placeholder="请输入用户名"
                       v-model="userName">
          <img src="./user_name.png" class="icon" slot="left">
        </md-input-item>
        <md-input-item name="userPwd" placeholder="请输入密码"
                       type="password"
                       v-model="userPwd">
          <img src="./password.png" class="icon" slot="left">
        </md-input-item>
        <md-input-item name="authCode" placeholder="请输入验证码"
                       v-model="authCode">
          <img src="./phone_code.png" class="icon" slot="left">
          <img slot="right" class="code"
               :src="codeImg" @click="loadVerificationCode">
        </md-input-item>
        <div class="remember-box" @click="rememberMe = !rememberMe">
          <i class="icon iconfont icon-checked" v-if="rememberMe"></i>
          <i class="icon iconfont icon-check" v-else></i>
          <p>记住密码</p>
        </div>
        <div class="btn-box">
          <md-button class="submit-btn" round @click="submit">登录</md-button>
          <div class="phone-login" @click="showPhoneLogin = true">手机验证码登陆>></div>
        </div>
      </md-field>
    </form>
    <form v-else>
      <!--解决浏览器自动填充账号密码的问题-->
      <input type="text" name="username" style="position: absolute;z-index: -99;height: 0;">
      <input type="password" name="password" style="position: absolute;z-index: -99;height: 0;">
      <md-field>
        <md-input-item name="phoneNumber" placeholder="请输入手机号"
                       v-model="phoneNumber">
          <img src="./user_name.png" class="icon" slot="left">
        </md-input-item>
        <md-input-item name="phoneCode" placeholder="请输入验证码"
                       v-model="phoneCode">
          <img src="./phone_code.png" class="icon" slot="left">
          <md-button class="sms-code-btn" @click="getSmsCode"
                     :type="sendSmsCodeState > 0 ? 'disabled' : 'default'"
                     slot="right" round>{{sendSmsCodeStateText}}
          </md-button>
        </md-input-item>
        <div class="btn-box">
          <md-button class="submit-btn" round @click="phoneSumbit">登录</md-button>
          <div class="phone-login" @click="showPhoneLogin = false">账号密码登陆>></div>
        </div>
      </md-field>
    </form>
  </div>
</template>

<script type="text/ecmascript-6">
import {
  Dialog,
  Button,
  Field,
  InputItem
} from 'mand-mobile';
import {
  encryptBySHA1,
  encryptByBase64,
  decryptByBase64
} from '@/utils';
import { getVerificationCode, sendSmsCode, login, loginBySmsCode } from '@/api/login';

export default {
  components: {
    [Dialog.name]: Dialog,
    [Button.name]: Button,
    [Field.name]: Field,
    [InputItem.name]: InputItem
  },
  data() {
    return {
      userName: '',
      userPwd: '',
      authCode: '',
      codeImg: '',
      imageId: '',
      rememberMe: false,
      phoneNumber: '',
      showPhoneLogin: false,
      phoneCode: '',
      sendSmsCodeState: 0
    };
  },
  computed: {
    sendSmsCodeStateText() {
      if (this.sendSmsCodeState === 0) return '发送验证码';
      return `${this.sendSmsCodeState}s后重新获取`;
    }
  },
  created() {
    const t = localStorage.getItem('t');
    if (t) {
      const userInfo = decryptByBase64(t).split(':');
      this.userName = userInfo[0];
      this.userPwd = userInfo[1];
      this.rememberMe = true;
    }
    this.loadVerificationCode();
  },
  methods: {
    loadVerificationCode() {
      getVerificationCode().then(result => {
        this.codeImg = `data:image/png;base64,${result.image}`;
        this.imageId = result.imageid;
      });
    },
    getSmsCode() {
      if (!this.phoneNumber.trim()) {
        Dialog.alert({ content: '手机号不能为空' });
        return;
      }
      this.getSmsCodeTimer();
      sendSmsCode(this.phoneNumber).then(result => {
        const data = result;
        if (data.statusCode !== 200) {
          Dialog.alert({ content: data.message });
        }
      }).catch(error => {
        Dialog.alert({ content: error });
      });
    },
    getSmsCodeTimer() {
      this.sendSmsCodeState = 60;
      this.timer = setInterval(() => {
        this.sendSmsCodeState -= 1;
        if (this.sendSmsCodeState === 0) clearInterval(this.timer);
      }, 1000);
    },
    submit() {
      if (!this.userName.trim()) {
        Dialog.alert({ content: '手机号不能为空' });
        return;
      }
      if (!this.userPwd.trim()) {
        Dialog.alert({ content: '密码不能为空' });
        return;
      }
      if (!this.authCode.trim()) {
        Dialog.alert({ content: '验证码不能为空' });
        return;
      }
      const payload = {
        accountType: 'system_manager',
        userName: this.userName,
        userPwd: encryptBySHA1(this.userPwd),
        sessionId: this.imageId,
        authCode: this.authCode
      };
      if (this.rememberMe) {
        localStorage.setItem('t', encryptByBase64(`${this.userName}:${this.userPwd}`));
      } else {
        localStorage.removeItem('t');
      }
      login(payload).then(result => {
        if (result.statusCode === 1) {
          this.$store.dispatch('setUserInfo', result.entity).then(() => {
            this.$router.replace({
              name: 'home',
              query: { timestamp: new Date().getTime() }
            });
          });
        } else {
          Dialog.alert({ content: result.message || '请求失败' });
          this.loadVerificationCode();
        }
      }).catch(error => {
        // this.loadVerificationCode();
        Dialog.alert({ content: error.response.data.error_exception || '请求失败' });
      });
    },
    phoneSumbit() {
      if (!this.phoneNumber.trim()) {
        Dialog.alert({ content: '手机号不能为空' });
        return;
      }
      if (!this.phoneCode.trim()) {
        Dialog.alert({ content: '手机验证码不能为空' });
        return;
      }
      const params = {
        userName: this.phoneNumber,
        authCode: this.phoneCode
      };
      loginBySmsCode(params).then(result => {
        if (result.statusCode === 200) {
          this.$store.dispatch('setUserInfo', result.entity).then(() => {
            this.$router.replace({
              name: 'home',
              query: { timestamp: new Date().getTime() }
            });
          });
        } else {
          Dialog.alert({ content: result.message });
        }
      }).catch(error => {
        Dialog.alert({ content: error });
      });
    }
  }
};
</script>

<style lang="stylus" scoped>
  .wrapper
    position : relative
    height : 100%
    width : 100%
    background : url("./background.png") no-repeat 50% 0
    background-size : cover

  .md-field
    position : absolute
    top : 45%
    left : 50%
    transform : translate(-50%, -50%)
    padding : 0 40px
    width : 100%
    max-width : 640px
    background : transparent
    /deep/ .md-field-content
      .md-field-item
        .md-field-item-content
          &:before
            height : 0
        .md-input-item-input
          border-radius : 80px
          height : 80px
          background : #fff
          padding-left : 80px
          font-size : 28px
      .md-field-item-left
        position : absolute
        left : 20px
        z-index : 999
      .icon
        width : 40px
        height : 40px

  .btn-box
    padding : 15px 0

  .md-button
    height : 80px
    &:after
      border : none
    &.submit-btn
      background-color : #81e1ff
      color : #fff
    &.sms-code-btn
      padding : 0 10px
      min-width : 200px
      font-size : 24px

  .code
    margin-left : 20px
    height : 72px
    width : 200px

  .remember-box
    padding : 15px
    line-height : 40px
    font-size : 28px
    color : #fff
    display : flex
    align-items : center
    .icon
      font-size : 40px
      margin-right : 10px
      color : #fff

  .phone-login
    font-size : 28px
    color : #fff
    text-align : center
    padding : 30px 0
    cursor : pointer
</style>
